﻿using Prism.Commands;
using Prism.Mvvm;
using StarryEdge.Core.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace StarryEdge.Menu.User.Models
{
    public class UIRoleItem : BindableBase
    {
        private UIRoleItem _parent;
        public UIRoleItem(UIRoleItem parent, bool isEdit)
        {
            _isEdit = isEdit;
            _parent = parent;
        }
        private List<UIRoleItem> childs = new List<UIRoleItem>();
        private bool _isEdit;
        public void AddChild(UIRoleItem child)
        {
            childs.Add(child);
        }

        private bool isChildOpen = true;

        public bool IsChildOpen
        {
            get => (_parent?.IsChildOpen ?? true) && isChildOpen;
            set
            {
                isChildOpen = value;
                SetChildVisibility();
            }
        }
        public Visibility HasChild => childs.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
        public Visibility RootVisibility => childs.Count > 0 ? Visibility.Collapsed : Visibility.Visible;
        public Visibility IsEdit => _isEdit ? Visibility.Visible : Visibility.Collapsed;

        public string Title { get; set; }
        public string Name { get; set; }
        /// <summary>
        /// 1 菜单目录 2 输入 3 事件
        /// </summary>
        public int Level { get; set; }

        public UIRoleItemModel SelectUIRole { get; set; }
        public ObservableCollection<UIRoleItemModel> GuidRoles { get; set; } = new ObservableCollection<UIRoleItemModel>();

        private DelegateCommand childOpenChangeCommand;

        public DelegateCommand ChildOpenChangeCommand => childOpenChangeCommand ?? (childOpenChangeCommand = new DelegateCommand(childOpenChange));

        private void childOpenChange()
        {
            IsChildOpen = !IsChildOpen;
            SetChildVisibility();
        }

        public Visibility VisibleState => (_parent?.IsChildOpen ?? true) ? Visibility.Visible : Visibility.Collapsed;

        public DelegateCommand<UIRoleItemModel> Selection => new DelegateCommand<UIRoleItemModel>(sender =>
        {
            SelectUIRole = sender;
        });

        private void changeOpenState()
        {
            RaisePropertyChanged(nameof(IsChildOpen));
            RaisePropertyChanged(nameof(VisibleState));
        }

        public void SetChildVisibility()
        {
            changeOpenState();
            foreach (var item in childs)
            {
                item.SetChildVisibility();
            }
        }
    }
}
